package news.paper.tintuc.tinnong.docbao.doctin.GCM;

import news.paper.tintuc.tinnong.docbao.doctin.AppController;
import news.paper.tintuc.tinnong.docbao.doctin.controller.ApiParams;
import news.paper.tintuc.tinnong.docbao.doctin.controller.RequestListener;

import org.json.JSONObject;

import android.app.Activity;

import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.google.android.gcm.GCMRegistrar;

public class SendGCM {
	public static void sendGCM(final String PackageName, String IMEI,
			String SenderID, final RequestListener listener) {
		listener.begin();
		ApiParams apiParams = new ApiParams(
				"http://appmanage.tienich360.com/Service/AppManageService.asmx/insertGCM?");
		apiParams.init();
		apiParams.addParams("PackageName", PackageName);
		apiParams.addParams("IMEI", IMEI);
		apiParams.addParams("SenderID", SenderID);
		JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
				apiParams.toString(), null,
				new Response.Listener<JSONObject>() {

					@Override
					public void onResponse(JSONObject response) {
						System.out.println("data: " + response.toString());
						listener.success(response);
					}
				}, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {
						listener.fail(error.getMessage());
					}
				}) {
		};
		AppController.getInstance().addToRequestQueue(jsonObjReq);
	}

	public static void sendgcm(String SenderID_, String PackageName_,
			String IMEI_) {
		if (SenderID_.length() > 50)
			sendGCM(PackageName_, IMEI_, SenderID_, new RequestListener() {

				@Override
				public void success(Object response) {

				}

				@Override
				public void fail(String message) {

				}

				@Override
				public void begin() {

				}
			});
	}

	public static void registerGCM(Activity activity, String imei) {
		String regId = GCMRegistrar.getRegistrationId(activity);
		if (regId.equals("")) {
			GCMRegistrar.register(activity, GCM_Constant.PROJECT_ID);
			regId = GCMRegistrar.getRegistrationId(activity);
		} else {
		}
		String PACKAGE_NAME = activity.getApplicationContext().getPackageName();
		SendGCM.sendgcm(regId, PACKAGE_NAME, imei);
	}
}
